package com.eurasia.assignment.service;

import com.eurasia.assignment.domain.Role;
import com.eurasia.assignment.domain.User;
import com.eurasia.assignment.infrastructure.repository.RoleRepository;
import com.eurasia.assignment.infrastructure.repository.UserRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    private final UserRepository userRepository;
    private final RoleRepository roleRepository;
    private final PasswordEncoder passwordEncoder;

    public UserService(UserRepository userRepository, RoleRepository roleRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.passwordEncoder = passwordEncoder;
    }

    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public User registerUser(User user) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置默认角色为ROLE_USER
        Role userRole = roleRepository.findByName("ROLE_USER")
                .orElseGet(() -> roleRepository.save(new Role("ROLE_USER")));
        user.setRoles(Collections.singleton(userRole));

        return userRepository.save(user);
    }
    
    public User registerAdminUser(User user, String adminCode) {
        // 验证管理员注册码
        if (adminCode == null || !adminCode.equals("ADMIN_SECRET_CODE")) {
            throw new RuntimeException("管理员注册码无效");
        }
        
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置角色为ROLE_ADMIN
        Role adminRole = roleRepository.findByName("ROLE_ADMIN")
                .orElseGet(() -> roleRepository.save(new Role("ROLE_ADMIN")));
        user.setRoles(Collections.singleton(adminRole));

        return userRepository.save(user);
    }

    /**
     * 注册教师用户
     * @param user 用户信息
     * @param teacherCode 教师注册码
     * @return 创建的用户对象
     */
    public User registerTeacherUser(User user, String teacherCode) {
        // 验证教师注册码
        if (teacherCode == null || !teacherCode.equals("TEACHER_SECRET_CODE")) {
            throw new RuntimeException("教师注册码无效");
        }
        
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置角色为ROLE_TEACHER
        Role teacherRole = roleRepository.findByName("ROLE_TEACHER")
                .orElseGet(() -> roleRepository.save(new Role("ROLE_TEACHER")));
        user.setRoles(Collections.singleton(teacherRole));

        return userRepository.save(user);
    }

    public boolean validateUser(String username, String password) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            return passwordEncoder.matches(password, user.getPassword()) && user.isEnabled();
        }
        return false;
    }
    
    public List<User> findAllUsers() {
        return userRepository.findAll();
    }
    
    /**
     * 删除指定ID的用户
     * @param userId 用户ID
     * @return 如果用户存在并成功删除返回true，否则返回false
     */
    public boolean deleteUser(Long userId) {
        if (userRepository.existsById(userId)) {
            userRepository.deleteById(userId);
            return true;
        }
        return false;
    }
}